# -*- coding:utf-8 -*-

# @Time    : 2023/4/18 11:59
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @File    : get_script_strategy.py
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

#调取openai的api获取对话的话术策略
# -*- coding:utf-8 -*-

# @Time    : 2023/3/3 14:36
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @Software: uplift

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #


import re
import csv
import openai
import time
import tqdm
import pandas as pd
from openpyxl import load_workbook, Workbook
openai.api_key = "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"  # supply your API key however you choose


def get_script_strategy(content):
    # 读取xlsx文件
    start_time = time.time()
    completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", temperature = 0, messages=[
        {"role": "system",
         "content": """
         你是个专业的保险销售员，在一个电话销售百万医疗保险的场景，你需要分别给出下面这些对话的话术策略，话术策略用简洁的短语表示，短语在6个字左右，短语间用-连接，输出的内容仅包含话术策略,且只有一句话，相同或近似的话术需要保障输出的话术策略的一致性：
###
1.话术：一般医社保可能只能报个百分之六七十，很多进口药自费药报不了，那给您升级之后的保障服务，可以把医社保不报都给您报了，合同约定是100%报销的，同时可以让家人享受同样的保障，费用也很轻松，首月几块钱就可以了，您目前结婚了嘛？
1.策略：医社保不全-保障全面-进口药自费药全报销-100%报销-家人同享-费用轻松-问婚姻状况
###
2.话术：喂，您好~请问您是**先生/女士吧？
2.策略：个人信息确认-礼貌称呼
###
3.话术：您好，我是泰康的客户经理，我姓刘，今天致电是给您做个回访，您之前有免费领取过咱们泰康的一个意外险，这个您还记得嘛？
3.策略：建立关系-自我介绍-回访目的-免费保险提醒
###
4.话术：那今天给您致电，是泰康26周年庆统一给老客户的保单做了升级，升级成重疾，意外，医疗三险合一的全险，可以很好的和医社保新农合做补充，因为医社保是有一定报销比例的，并且进口药自费药都是没办法报销的，这个您知道吧？
4.策略：致电目的-周年庆升级-全险补充-报销限制-知晓确认
###
5.话术：可能是您忙忘了，不过没关系，那今天给您致电，是泰康26周年庆统一给老客户的保单做了升级，升级成重疾，意外，医疗三险合一的全险，可以很好的和医社保新农合做补充，因为医社保是有一定报销比例的，并且进口药自费药都是没办法报销的，这个您知道吧？
5.策略：理解遗忘-活动提及-升级解释-医保补充-报销限制-知晓确认
###
6.话术：我的意思是说，您之前有领咱们泰康一个免费意外险，今天给您致电，是泰康26周年庆统一给老客户的保单做了升级，升级成重疾，意外，医疗三险合一的全险，可以很好的和医社保新农合做补充，因为医社保是有一定报销比例的，并且进口药自费药都是没办法报销的，这个您知道吧？
6.策略：意图阐述-保单升级-三险合一-医保补充-报销限制-知晓确认
###
7.话术：好的，抱歉打扰您了，感谢您的接听，祝您生活愉快，再见！
7.策略：感谢接听-祝福生活-结束通话
###
8.话术：您再试下，看能不能连个无线，我带您去看下具体的保障内容
8.策略：无线连接-引导查看保障内容
###
9.话术：抱歉，刚刚没太听清，冒昧问下您是做什么工作的啊？
9.策略：道歉解释-询问职业信息
###
10.话术：
"""
    },
        {"role": "user",
         "content": content + ',10.策略:'}])
    result = completion.choices[0].message.content
    return result


def save_script_strategy():
    df = pd.read_excel('data/黑牛1call-Bot话术和录音编号.xls')
    result = []
    for index, row in df.iterrows():
        script_strategy = get_script_strategy(row["场景话术"])
        row["话术策略"] = script_strategy
        print(row["场景话术"] + "——的话术策略是：" + row["话术策略"])
        result.append(row)
    result_df = pd.DataFrame(result)
    result_df.to_csv('data/黑牛1call-Bot话术和录音编号.csv', index=False, encoding='utf_8_sig')

#加载已有话术策略缓存
def load_script_strategy():
    df = pd.read_csv('../data_dialogue/dilogue_data/script_strategy_dict.csv')
    script_strategy_dict = {}
    for index, row in df.iterrows():
        script_strategy_dict[row["场景话术"]] = row["话术策略"]
    return script_strategy_dict


#读取人机对话数据，识别其中所有机器人的话术策略
def save_bot_script_strategy():
    df = pd.read_csv('data/tag_dialogue_data.csv')
    script_strategy_dict = load_script_strategy()
    result = []
    for index, row in df.iterrows():
        if row["role"] == "机器人":
            if row["predict_tag"]:
                if result and result[-1]["role"] == "用户":
                    result[-1]["predict_tag"] = row["predict_tag"]
                row["predict_tag"] = ""


            if "喂，您好~请问您是" in row["clean_content"]:
                row["predict_tag"] = "个人信息确认-礼貌称呼"
            elif "没听清，您是" in row["clean_content"]:
                row["predict_tag"] = "道歉解释-个人信息确认-礼貌称呼"
            elif row["clean_content"] in script_strategy_dict:
                row["predict_tag"] = script_strategy_dict[row["clean_content"]]
            else:
                script_strategy = get_script_strategy(row["clean_content"])
                script_strategy_dict[row["clean_content"]] = script_strategy
                row["predict_tag"] = script_strategy
            print(row["clean_content"] + "——的话术策略是：" + row["predict_tag"])
        result.append(row)
    script_strategy_dict_df = pd.DataFrame(script_strategy_dict.items(), columns=['场景话术', '话术策略'])
    script_strategy_dict_df.to_csv('data/script_strategy_dict.csv', index=False, encoding='utf_8_sig')

    result_df = pd.DataFrame(result)
    result_df.to_csv('data/tag_dialogue_data_with_strategy.csv', index=False, encoding='utf_8_sig')


def process_label(labels):

    sign = 0
    if '强烈拒绝' in labels:
        return '用户主动表示:强烈拒绝'

    if '用户主动' in labels:
        sign = 1

    for label in labels.split(','):
        if sign == 1 and '用户主动' in label:
            return label

        if sign == 2 and '实体' in label:
            return label

    return label


def load_script():

    wb = load_workbook('../data_dialogue/dilogue_data/script_strategy_dict.xlsx')
    ws = wb[wb.sheetnames[0]]

    script_strategy_dict = dict()
    for i, row in tqdm.tqdm(enumerate(ws.values)):
        if i != 0:
            # print( row )
            script_strategy_dict[row[0]] = row[1]

    return script_strategy_dict


def process_msg(msg_content, speaker_type):

    FAQ_name = ''
    return_content = list()
    if speaker_type == 'IVR':
        for content in msg_content.split('|')[1:]:
            if content.split('#')[0].replace(' ', '').replace('}', '').replace('@@notbreak@@', '').replace('您不要挂电话，马上为您服务', ''):
                return_content.append(content.split('#')[0].replace(' ', '').replace('}', '').replace('@@notbreak@@', '').replace('您不要挂电话，马上为您服务', ''))

        if '播报faq答案' in msg_content:
            pattern = re.compile(r'FAQ.{0,10}》')
            if pattern.findall(msg_content):
                FAQ_name = pattern.findall(msg_content)[0].replace('FAQ:', '').replace('》', '')

    else:
        return_content.append(msg_content.split(']')[-1].replace('您不要挂电话马上为您服务', ''))


    return '，'.join(return_content), return_content, FAQ_name


def seat_sentence_from_dialogue():

    file_path = '../data_dialogue/dilogue_data/_2199_2023-03-30 00_00_00_2023-03-30 23_10_00_100.xlsx'
    wb = load_workbook(file_path)
    ws = wb[wb.sheetnames[0]]

    wb_w = Workbook()
    ws_w = wb_w.active
    ws_w.append([
        '坐席话术', '话术标签'
    ])

    customer_id_dict = dict()
    seat_sentence_set = set()
    for i, row in tqdm.tqdm(enumerate(ws.values)):

        if i != 0 and row[0]:
            customer_id = row[0]
            role = row[4]
            origin_sentence = row[5]

            sentence, sentence_list, FAQ_name = process_msg(origin_sentence, 'IVR' if role == '销售员' else role)
            if FAQ_name:
                ws_w.append([
                    sentence_list[0], FAQ_name+'回复'
                ])
                sentence_list = sentence_list[1:]

            if customer_id not in customer_id_dict:
                customer_id_dict[customer_id] = list()
            customer_id_dict[customer_id].append([role, origin_sentence, sentence, sentence_list])


    for customer_id in tqdm.tqdm(customer_id_dict):
        for row in customer_id_dict[customer_id]:
            role = row[0]
            # sentence = row[2]
            if role == '销售员':
                for sentence in row[3]:
                    if "喂，您好~请问您是" in sentence:
                        sentence = "喂，您好~请问您是"
                    elif "没听清，您是" in sentence:
                        sentence = '没听清，您是'
                    elif '您是' in sentence:
                        sentence = '您是'

                    seat_sentence_set.add(sentence)

            if '马上为您服务' in row[1]:
                break

    seat_sentence_list = list(seat_sentence_set)

    for seat_sentence in tqdm.tqdm(seat_sentence_list):
        if "喂，您好~请问您是" in seat_sentence:
            print("个人信息确认-礼貌称呼")
            ws_w.append(['喂，您好~请问您是',])
        elif "没听清，您是" in seat_sentence:
            print('道歉解释-个人信息确认-礼貌称呼')
            ws_w.append(['没听清，您是', ])
        else:
            print( seat_sentence )
            # print( script_strategy_dict[seat_sentence] )
            ws_w.append([seat_sentence,])

    wb_w.save('./2199_0330_sentence_label.xlsx')


def seat_sentence_task():
    script_strategy_dict = load_script()

    wb = load_workbook('./2199_0330_sentence_label.xlsx')
    ws = wb[wb.sheetnames[0]]

    wb_w = Workbook()
    ws_w = wb_w.active
    ws_w.append([
        '坐席话术', '话术标签'
    ])

    for i, row in tqdm.tqdm(enumerate(ws.values)):
        if i != 0 and not row[1]:
            seat_sentence = row[0]

            try:
                print( script_strategy_dict[seat_sentence], seat_sentence )
                ws_w.append([
                    seat_sentence, script_strategy_dict[seat_sentence]
                ])
            except Exception as err:
                print( seat_sentence )
                for sentence in script_strategy_dict:
                    if seat_sentence in sentence:
                        ws_w.append([
                            seat_sentence,
                        ])
                        break

    wb_w.save('./2199_0330_sentence_label_final2.xlsx')


if __name__ == '__main__':

    # save_bot_script_strategy()
    content = """
    我是泰康保险的，您之前投保了一份咱们泰康的百万医疗保险，已经付过首月保费了。今天给您来电是做售后服务通知的，您当时投保付过首月保费之后啊，有一个一键升级忘记点了，也是为了避免日后报销比例对您有影响，我这边带您进行一个保单升级，你看我这样讲好理解吧？
    """
    result = get_script_strategy(content)
    print(result)

    # seat_sentence_from_dialogue()

    # load_script()



